import http from "./http-base.js";
import store from "../store";
import { Message } from "element-ui";

/**
 * @description _tips
 */
const TipConfig = (
  config = {
    on: true, //or false 默认true
    status: false, // 加载显示与否
    msg: "拼命加载", // 提示消息
    // icon: "icon", // 提示图标
    bg: "rgba(0, 0, 0, 0.8)" // 提示背景
  }
) => config;

http.interceptors.request.use(
  config => {
    let { on, msg } = TipConfig(config._tips);
    on && store.commit("loading", { status: true, msg });
    //加载api-token
    config.headers["api-token"] = store.state.loginInfo.token;
    return config;
  },
  err => {
    Message.error("网络异常，请检查网络环境后重试");
    store.commit("loading", { status: false });
    return Promise.reject(err);
  }
);
http.interceptors.response.use(
  resp => {
    const {
      data: { code, msg }
    } = resp;
    switch (code) {
      case "0000":
        break;
      case "4444":
        Message.error(msg);
        break;
      case "9999":
        Message.warning(msg);
        break;
      case "8888":
        Message(msg);
        break;
      default:
        Message.error("服务异常");
        break;
    }

    store.commit("loading", { status: false });
    return resp;
  },
  error => {
    Message.error("网络异常，请检查网络环境后重试");
    store.commit("loading", { status: false });
    return Promise.reject(error);
  }
);
